#include "head.hpp"
void cleanup_unlock(void *p)
{
    pthread_mutex_t *lock = (pthread_mutex_t *)p;
    pthread_mutex_unlock(lock);
}
int worker(int net_fd)
{
    send(net_fd, "hello", 5, MSG_NOSIGNAL);
    return 0;
}
void *thread_main(void *args)
{
    status_t *status = (status_t *)args;
    while (true)
    {
        int net_fd = 0;
        // // v1
        // pthread_mutex_lock(&status->lock);
        // pthread_cleanup_push(cleanup_unlock, &status->lock);
        // while (status->queue.size <= 0)
        // {
        //     pthread_cond_wait(&status->cond, &status->lock);
        // }
        // net_fd = status->queue.head->net_fd;
        // deQueue(&status->queue);
        // pthread_cleanup_pop(1);
        // v2
        pthread_mutex_lock(&status->lock);
        while (status->queue.size <= 0 && status->exit_flag == 0)
        {
            pthread_cond_wait(&status->cond, &status->lock);
        }
        if (status->exit_flag != 0)
        {
            pthread_mutex_unlock(&status->lock);
            pthread_exit(nullptr);
        }
        net_fd = status->queue.head->net_fd;
        deQueue(&status->queue);
        pthread_mutex_unlock(&status->lock);

        worker(net_fd);
        close(net_fd);
    }
    return nullptr;
}
int init_thread(status_t *status)
{
    for (int i = 0; i < status->size; i++)
    {
        pthread_create(&status->thread[i], nullptr, thread_main, status);
    }
    return 0;
}